package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.LoginDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.AppJwtUtil;
import com.sun.javafx.collections.MappingChange;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        //1,判断入参是否为空
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2,校验手机号和密码是否存在
        String phone = dto.getPhone();
        String password = dto.getPassword();
        if(StringUtils.isEmpty(phone)&&StringUtils.isEmpty(password)){
            //游客登录
            String token = AppJwtUtil.getToken(0L);
            Map<String, Object> map=new HashMap<>();
            map.put("user",null);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }

        //3，正常登录
        //3.1查询手机号是否存在
        LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper();
        wrapper.eq(ApUser::getPhone,phone);
        ApUser apUser = apUserMapper.selectOne(wrapper);
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //3.2比对密码
        String salt = apUser.getSalt();
        String passwordFromDb = apUser.getPassword();
        String passwordFromMd5 = DigestUtils.md5DigestAsHex((salt + password).getBytes());
        if(!passwordFromDb.equals(passwordFromMd5)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //3.3生成token
        String token = AppJwtUtil.getToken(apUser.getId().longValue());
        //清空敏感数据
        apUser.setPassword("");
        apUser.setSalt("");
        //user+token
        Map<String, Object> map=new HashMap<>();
        map.put("user",apUser);
        map.put("token",token);
        //3.4返回数据
        return ResponseResult.okResult(map);

    }
}